<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\BillsModel;
use Illuminate\Support\Facades\DB;

class BillsDao extends BaseDao
{
    public static function bill_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = BillsModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'type'),function ($query)use ($params){
            $query->where('type',$params['type']);
        });
        $query->when(checkIsHasField($params,'prices_type'),function ($query)use ($params){
            if($params['prices_type'] == 'in'){
                $query->where('price','>',0);
            }else if($params['prices_type'] == 'out'){
                $query->where('price','<',0);
            }
        });

        return $query->orderByDesc('created_at');
    }


    /**
     * @desc 余额变动
     * @param int $price
     * @param int $user_id
     * @param string $title
     * @return void
     * @throws SysExceptions
     */
    public static function moneysUpdate(float $price = 0, int $user_id = 0, string $title = '')
    {
        try {
            self::bill_query()->create([
                'user_id'=>$user_id,
                'price'=>$price,
                'title'=>$title,
                'type'=>0
            ]);
            UsersDao::builder_query(['user_id'=>$user_id])->increment('money',$price);
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function moneysLog(array $params): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $params['type'] = 0;
        return self::bill_query($params)->paginate();
    }


    public static function xiaoFeiLog(array $params): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $params['type'] = 1;
        return self::bill_query($params)->paginate();
    }



    public static function logs(array $params)
    {
        return self::bill_query($params)->paginate();
    }



}
